<template>
  <div class="goods-detail">
    <!-- 返回按钮 -->
    <div class="back-button">
      <router-link to="/">
        <i class="el-icon-arrow-left"></i> 返回
      </router-link>
    </div>

    <!-- 商品详情容器（Flex 布局） -->
    <div class="detail-container" v-if="goodsDetail">
      <!-- 商品图片 -->
      <div class="goods-pic">
        <img 
          :src="getImageUrl(goodsDetail.pic)" 
          alt="商品图片" 
          @error="handleImageError"
        />
      </div>

      <!-- 商品信息（右侧） -->
      <div class="goods-info">
        <h2 class="title">商品详情</h2>
        <p class="info-item">商品名称：{{ goodsDetail.name }}</p>
        <p class="info-item">商品价格：¥{{ goodsDetail.price }}</p>
        <p class="info-item">商品ID：{{ goodsDetail.id }}</p>
        <p class="info-item">剩余量：{{ goodsDetail.remaining }}</p>
        
        <!-- 购买份数区域（优化后：更紧凑小巧） -->
        <div class="purchase-area">
          <div class="count-control">
            <button class="buy-button minus-button" @click="decrementPurchase">
              <i class="el-icon-minus">-</i>
            </button>
            <span class="count-display"> {{ purchaseCount }} </span>
            <button class="buy-button plus-button" @click="incrementPurchase">
              <i class="el-icon-plus">+</i>
            </button>
          </div>
        </div>
        
        <!-- 操作按钮区域（优化后：更紧凑） -->
        <div class="action-buttons">
          <button class="cart-button" @click="addToCart">
            <i class="el-icon-shopping-cart"></i> 加入购物车
          </button>
          <button class="purchase-button" @click="openPurchaseDialog">
            <i class="el-icon-shopping-cart-full"></i> 立即购买
          </button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <el-loading-spinner></el-loading-spinner>
      <p>加载中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error">
      <p>获取商品详情失败，请刷新重试</p>
      <el-button @click="fetchGoodsDetail">重试</el-button>
    </div>

    <!-- 购买确认弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      title="确认购买" 
      width="30%"
      center
    >
      <div class="dialog-content">
        <p>商品名称：{{ goodsDetail.name }}</p>
        <p>购买份数：{{ purchaseCount }}</p>
        <p>单份价格：¥{{ goodsDetail.price }}</p>
        <p class="total-price">总价格：¥{{ totalPrice }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPurchase">确认购买</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElDialog, ElButton, ElLoading } from 'element-plus';

export default {
  name: 'GoodsDetail',
  components: {
    ElDialog,
    ElButton
  },
  data() {
    return {
      goodsDetail: {},       // 商品详情数据
      loading: false,        // 加载状态
      error: false,          // 错误状态
      purchaseCount: 0,      // 购买份数
      dialogVisible: false,  // 弹窗显示状态
      isLoggedIn: false,
      userInfo: {},
      loginUserId: localStorage.getItem('userId') || null
    };
  },
  created() {
    this.checkLoginStatus();
    this.fetchGoodsDetail();
  },
  computed: {
    // 计算总价格（单价 × 份数）
    totalPrice() {
      return (parseFloat(this.goodsDetail.price || 0) * this.purchaseCount).toFixed(2);
    }
  },
  methods: {
    async fetchGoodsDetail() {
      this.loading = true;
      this.error = false;

      try {
        const goodsId = this.$route.params.id;
        const response = await axios.get(`http://127.0.0.1:8080/goods/${goodsId}`);
        
        if (response.data) {
          this.goodsDetail = response.data;
        } else {
          throw new Error('商品数据为空');
        }
      } catch (error) {
        console.error('获取商品详情失败：', error);
        this.error = true;
      } finally {
        this.loading = false;
      }
    },
    getImageUrl(picName) {
      return `http://localhost:8080/images/${picName}`;
    },
    handleImageError(e) {
      e.target.src = 'https://picsum.photos/400/400?random=error';
    },
    // 增加购买份数
    incrementPurchase() {
      if (this.purchaseCount < this.goodsDetail.remaining) {
        this.purchaseCount++;
      } else {
        ElMessage.error(`已达到最大可购买数量（库存: ${this.goodsDetail.remaining}）`);
      }
    },
    // 减少购买份数
    decrementPurchase() {
      if (this.purchaseCount > 0) {
        this.purchaseCount--;
      } else {
        ElMessage.warning('购买份数不能小于0');
      }
    },
    // 打开购买弹窗
    openPurchaseDialog() {
      if (!this.isLoggedIn) {
        ElMessage.warning('请先登录再进行购买');
        this.$router.push('/sign').catch(err => {
          console.warn('路由跳转失败:', err);
        });
        return;
      }
      // 校验购买份数
      if (this.purchaseCount <= 0) {
        ElMessage.warning('请先选择购买份数');
        return;
      }
      this.dialogVisible = true;
    },
    // 提交购买（核心修改：状态提示与跳转路径）
    async submitPurchase() {
      this.dialogVisible = false;
      // 添加加载动画提升体验
      const loading = ElLoading.service({ text: '提交订单中...' });
      try {
        const response = await axios.post(
          'http://127.0.0.1:8080/api/buys/purchases',
          {
            userId: parseInt(this.loginUserId),
            goodsId: this.goodsDetail.id,
            quantity: this.purchaseCount,
            totalPrice: parseFloat(this.totalPrice)
          },
          {
            headers: {
              'Content-Type': 'application/json'
            }
          }
        );

        if (response.data.success) {
          // 提示订单状态为"待发货"，明确无支付环节
          ElMessage.success('购买成功！订单已创建，状态：待发货');
          // 跳转至"我的订单"页面（路径匹配导航配置的/about）
          this.$router.push('/about').catch(err => {
            console.warn('路由跳转失败:', err);
          });
          this.purchaseCount = 0;
        } else {
          ElMessage.error(response.data.message || '购买失败，请重试');
        }
      } catch (error) {
        console.error('下单失败：', error.response?.data || error.message);
        ElMessage.error(
          error.response?.data?.message || '系统异常，购买失败'
        );
      } finally {
        loading.close(); // 关闭加载动画
      }
    },
    // 加入购物车
    async addToCart() {
      // 登录校验
      if (!this.isLoggedIn) {
        ElMessage.warning('请先登录再加入购物车');
        this.$router.push('/sign').catch(err => {
          console.warn('路由跳转失败:', err);
        });
        return;
      }
      
      // 购买份数校验
      if (this.purchaseCount <= 0) {
        ElMessage.warning('请先选择购买份数');
        return;
      }
      
      // 库存校验
      if (this.purchaseCount > this.goodsDetail.remaining) {
        ElMessage.error(`购买数量超过库存（当前库存: ${this.goodsDetail.remaining}）`);
        return;
      }
      
      try {
        // 构造购物车数据
        const cartData = {
          userId: parseInt(this.loginUserId),
          goodsId: this.goodsDetail.id,
          quantity: this.purchaseCount,
          goodsName: this.goodsDetail.name,
          price: parseFloat(this.goodsDetail.price)
        };
        
        // 设置请求头
        const headers = {
          'Content-Type': 'application/json'
        };

        // 调用购物车接口
        await axios.post('http://127.0.0.1:8080/api/buy/shoppingcart/add', cartData, { headers });
        
        ElMessage.success('加入购物车成功！');
        this.purchaseCount = 0;
      } catch (error) {
        console.error('加入购物车失败：', error);
        ElMessage.error('加入购物车失败，请重试');
      }
    },
    // 检查登录状态
    checkLoginStatus() {
      try {
        const storedUser = localStorage.getItem('userInfo');
        if (storedUser) {
          this.userInfo = JSON.parse(storedUser || '{}');
          this.isLoggedIn = true;
          this.loginUserId = this.userInfo.id;
        }
      } catch (err) {
        console.error('解析用户信息失败:', err);
        this.clearUserInfo();
      }
    },
    // 退出登录方法
    handleLogout() {
      try {
        this.clearUserInfo();
        this.isLoggedIn = false;
        this.userInfo = {};
        this.loginUserId = null;
        ElMessage.success('已退出登录');
        this.$router.push('/').catch(err => {
          console.warn('路由跳转失败:', err);
        });
      } catch (err) {
        console.error('退出登录过程出错:', err);
        this.isLoggedIn = false;
        this.userInfo = {};
        this.loginUserId = null;
        ElMessage.success('已退出登录');
      }
    },
    // 清除用户信息
    clearUserInfo() {
      try {
        if (localStorage) {
          localStorage.removeItem('userInfo');
          localStorage.removeItem('userId');
        }
      } catch (err) {
        console.warn('清除本地存储失败:', err);
      }
    }
  }
};
</script>

<style scoped>
.goods-detail {
  padding: 20px;
}

.back-button {
  margin-bottom: 20px;
}

.detail-container {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.goods-pic img {
  width: 300px;
  height: auto;
  border-radius: 4px;
}

.goods-info {
  flex: 1;
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 10px;
  font-size: 16px;
  color: #333;
}

/* 购买份数区域：优化为紧凑样式 */
.purchase-area {
  margin: 15px 0; /* 减少上下间距 */
  padding: 8px 12px; /* 缩小内边距 */
  background-color: #f5f7fa;
  border-radius: 6px;
  display: inline-block; /* 让容器只包裹内容宽度 */
}

.count-control {
  display: flex;
  align-items: center;
  gap: 8px; /* 缩小按钮间距 */
  height: 36px; /* 固定高度使整体更小巧 */
}

.buy-button {
  width: 36px; /* 缩小按钮尺寸 */
  height: 36px;
  padding: 0; /* 去除内边距 */
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.count-display {
  min-width: 40px; /* 固定数字显示宽度 */
  text-align: center;
  font-size: 16px;
  color: #333;
}

.minus-button {
  background-color: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.minus-button:hover {
  background-color: #f78989;
}

.plus-button {
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.plus-button:hover {
  background-color: #66b1ff;
}

/* 操作按钮区域：优化紧凑度 */
.action-buttons {
  margin-top: 15px; /* 减少与上方的距离 */
  display: flex;
  gap: 10px; /* 缩小按钮间距 */
  width: 100%;
  max-width: 400px; /* 限制最大宽度 */
}

.cart-button, .purchase-button {
  padding: 8px 16px; /* 缩小按钮内边距 */
  font-size: 14px; /* 减小字体 */
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px; /* 图标与文字间距缩小 */
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cart-button {
  background-color: #67c23a;
  color: white;
}
.cart-button:hover {
  background-color: #85ce61;
}

.purchase-button {
  background-color: #ff4d4f;
  color: white;
}
.purchase-button:hover {
  background-color: #ff7070;
}

.loading {
  text-align: center;
  padding: 50px 0;
}

.error {
  text-align: center;
  padding: 50px 0;
  color: #ff4d4f;
}

.dialog-content {
  text-align: left;
  padding: 10px 0;
}

.total-price {
  font-weight: bold;
  color: #ff4d4f;
  font-size: 18px;
  margin-top: 10px;
}
</style>